import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder();

export default function removeByIdResolveBuilder({
	model,
	balanceOps,
	permissionRequired,
	prepareFilter = ({ args }) => args,
}) {
	return async (root, args, { request }) => {
		const {
			auth: {
				credentials: { permissionMap, uid },
			},
			server: {
				methods: { calcBalance },
			},
		} = request;

		const filter = prepareFilter({ args, request });
		const item = await model.findOne(filter);
		const haveOtherUserPermission = permissionMap[`${permissionRequired}\x010`];
		if (item.uid.toString() !== uid && !haveOtherUserPermission) {
			const error = errorCodesBuilder['删除记录没有权限'];
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		try {
			await item.remove();
		} catch (err) {
			const error = errorCodesBuilder[''].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		try {
			await calcBalance({ uid: item.uid, ops: balanceOps });
		} catch (err) {
			const error = errorCodes[''].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		return item;
	};
}
